import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-http-bearer';
import { AuthService } from '../modules/user/services/auth.service';
import { RegexUtil } from '../utils/regex.util';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService, private readonly regexUtil: RegexUtil) {
    super();
  }

  /**
   * 验证token是否合法
   * @param token token值
   */
  async validate(token: string) {
    if (!token || !this.regexUtil.isUuid(token)) throw new UnauthorizedException();

    const user = await this.authService.decodeToken(token);
    if (!user) throw new UnauthorizedException();

    return user;
  }
}
